﻿using System.Data;
using AutoMapper;
using Dapper;
using MediatR;
using MyMES.Domain.yjb;
using MyMES.Error;
using MyMES.Infrastructure;
using MyMES.Infrastructure.Interface;
using MyMES.Writer.API.Application.Commends.settingCommand;
using MyMES.Writer.API.FileNlog;

namespace MyMES.Writer.API.Application.CommendHandlers.settingCommand
{
    public class AddPurchaseOrderCommandHandlers : IRequestHandler<AddPurchaseOrderCommand, APIResult<PurchaseOrder>>
    {
        private readonly IBaseRepository<PurchaseOrder> accreop;
        private readonly IMapper mapper;
        private readonly Nolgs nlogs;
        private readonly DatabaseContext db;

        public AddPurchaseOrderCommandHandlers(IBaseRepository<PurchaseOrder> accreop, IMapper mapper, Nolgs nlogs,DatabaseContext db)
        {
            this.accreop = accreop;
            this.mapper = mapper;
            this.nlogs = nlogs;
            this.db = db;
        }
        /// <summary>
        /// 日俺家采购
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIResult<PurchaseOrder>> Handle(AddPurchaseOrderCommand request, CancellationToken cancellationToken)
        {
            APIResult<PurchaseOrder> result = new APIResult<PurchaseOrder>();

            using (var connection = db.Connection)
            {
                if (connection.State != ConnectionState.Open)
                {
                    connection.Open();
                }
                request.WJId ??= new List<int>();
                using (var transaction = connection.BeginTransaction())
                {
                    try
                    {
                        var Arrival = mapper.Map<PurchaseOrder>(request); 
                        var model = mapper.Map<PurchaseOrder>(request);
                        string sql = @"insert into PurchaseOrder(OrderSubject,PurchaseOrderNumber,RelatedPurchaseRequisition,RelatedSalesOrder,PurchaseDate,SupplierName,ContactPerson,ContactPhone,Purchaser,PurchaseDepartment,ContactWay,RelatedProject,SettlementMethod,DeliveryAddress,Remarks,IsDelete) values(@OrderSubject,@PurchaseOrderNumber,@RelatedPurchaseRequisition,@RelatedSalesOrder,@PurchaseDate,@SupplierName,@ContactPerson,@ContactPhone,@Purchaser,@PurchaseDepartment,@ContactWay,@RelatedProject,@SettlementMethod,@DeliveryAddress,@Remarks,@IsDelete); SELECT LAST_INSERT_ID();";

                        var ArrivalId = await connection.ExecuteScalarAsync<int>(
                            sql,
                            Arrival,
                            transaction);

                        if (ArrivalId > 0)
                        {
                            if (request.WJId.Any())
                            {
                                const string sql1 = $"insert into PGZJ (PurchaseOrderId, SerialNumber) values (@PurchaseOrderId, @SerialNumber)";
                                foreach (var SerialNumber in request.WJId)
                                {
                                    await connection.ExecuteAsync(
                                        sql1,
                                        new
                                        {
                                            PurchaseOrderId = ArrivalId,
                                            SerialNumber = SerialNumber,
                                        }, transaction);
                                }
                            }
                        }
                        else
                        {
                            throw new Exception("插入 Arrivalmanagement 表失败，无法获取有效的 ArrivalId");
                        }

                        transaction.Commit();
                        var newdata = await connection.QueryFirstOrDefaultAsync<PurchaseOrder>("select * from PurchaseOrder where PurchaseOrderId = @PurchaseOrderId", new { PurchaseOrderId = ArrivalId });

                        result.Code = APIEnum.添加成功;
                        result.Msg = $"到票成功，销售订单数：{request.WJId.Count}";
                        result.data = newdata;

                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        throw new Exception("添加到票信息失败，事务已回滚", ex);
                    }
                }
            }

            return result;
        }
    }
}
